#include "entertainment.h"


int main(int argc, const char ** argv)
{
	int i;
	FILE * instream = stdin;
	FILE * outstream = stdout;
	
	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "-i") == 0)
		{
			if (instream != stdin)
			{
				/* already given -i */
				mtm_error(err_WrongArguments);
				goto cleanup;
			}
			i++;
			instream = fopen(argv[i], "r");
			if (instream == NULL)
			{
				/* failed to open file */
				mtm_error(err_OpenFailed);
				goto cleanup;
			}
		}
		else if (strcmp(argv[i], "-o") == 0)
		{
			if (outstream != stdout)
			{
				/* already given -o */
				mtm_error(err_WrongArguments);
				goto cleanup;
			}
			i++;
			outstream = fopen(argv[i], "w");
			if (outstream == NULL)
			{
				/* failed to open file */
				mtm_error(err_OpenFailed);
				goto cleanup;
			}
		}
		else 
		{
			/* invalid switch */
			mtm_error(err_WrongArguments);
			goto cleanup;
		}
	}
	
	process_file(instream, outstream);

cleanup:
	/* close the streams (only if we opened them) */
	if (instream != stdin && instream != NULL)
	{
		if (fclose(instream) != 0)
			mtm_error(err_CloseFailed);
			/* don't return immediately, first close other stream */
	}
	if (outstream != stdout && outstream != NULL)
	{
		if (fclose(outstream) != 0)
			mtm_error(err_CloseFailed);
	}
	
	/* the paper says to always return 0, regardless of status */
	return 0;
}


